<template>
  <div>
    <el-tree
      :data="categoryList"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandNodeKey"
      :allow-drop="allowDrop"
      show-checkbox
      node-key="catId"
      draggable
      @node-click="handleNodeClick"
    >
      <span
        class="custom-tree-node"
        slot-scope="{ node, data }"
      >
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="edit(data)"
          >
            修改
          </el-button>
          <el-button
            v-if="data.childrenList.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input
            v-model="category.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input
            v-model="category.icon"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitData"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      category: {
        catId: null, // 分类id
        name: '', // 分类名称
        parentCid: 0, // 父分id
        catLevel: 0, // 分类层级
        showStatus: 1, // 是否展示，逻辑删除标志
        sort: 0, // 排序
        productUnit: '', // 计量单位
        icon: '' // 图表
      }, // 新增分类对象
      categoryList: [],
      expandNodeKey: [], // 默认展开的节点
      dialogTitle: '', // 新增或编辑
      dialogType: '', // edit or add
      dialogVisible: false,
      defaultProps: {
        children: 'childrenList',
        label: 'name'
      }
    }
  },
  methods: {
    handleNodeClick (data) {
      console.log(data)
    },
    getCategoryList () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'post',
        data: this.$http.adornData()
      }).then(({ data }) => {
        console.log(data.data)
        this.categoryList = data.data
      })
    },
    // 添加分类
    addCategory () {
      console.log('添加菜单', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        console.log('新增成功')
        // 重新查询分类信息
        this.dialogVisible = false
        this.getCategoryList()
        this.expandNodeKey = [this.category.parentCid]
        this.$message({
          type: 'success',
          message: '新增成功!'
        })
      })
    },
    editCategory () {
      console.log('修改菜单', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        console.log('修改成功')
        // 重新查询分类信息
        this.dialogVisible = false
        this.getCategoryList()
        this.expandNodeKey = [this.category.parentCid]
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
        this.dialogVisible = false
        this.getCategoryList()
        this.expandNodeKey = [this.category.parentCid]
      })
    },
    append (data) {
      console.log('添加分类', data)
      this.dialogTitle = '添加'
      this.dialogType = 'add'
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel + 1
      // 若添加前修改过分类信息，属性设置为默认
      this.category.catId = null
      this.category.name = ''
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = 0
      this.category.showStatus = 1
    },
    edit (data) {
      console.log('修改分类', data)
      this.dialogTitle = '编辑'
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        console.log('查询分类信息', data)
        this.category.name = data.category.name
        this.category.catId = data.category.catId
        this.category.icon = data.category.icon
        this.category.productUnit = data.category.productUnit
        this.category.parentCid = data.category.parentCid
        this.category.sort = data.category.sort
        this.category.catLevel = data.category.catLevel
        this.category.showStatus = data.category.showStatus
      })
    },
    remove (node, data) {
      console.log('删除分类', node, data)
      let nodeData = data
      this.$confirm(`是否删除【${data.name}】菜单`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let delIds = [data.catId]
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(delIds, false)
        }).then(({ data }) => {
          console.log('删除成功')
          // 重新查询分类信息
          this.getCategoryList()
          this.expandNodeKey = [nodeData.parentCid]
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => { })
    },
    // 添加或修改类型
    submitData () {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else if (this.dialogType === 'edit') {
        this.editCategory()
      }
    },
    /**
     * 是否可拖拽
     * draggingNode 当前拖拽节点
     * dropNode 移动参照节点
     * type 移动位置 pre next inner
     * return boolean
     * **/
    allowDrop (draggingNode, dropNode, type) {
      // 被拖动的当前节点以及拖动参照节点的层级数不能 > 3
      // 被拖动节点的最大深度
      let draggingNodeDepth = this.getNodeDepth(draggingNode.data)
      console.log(draggingNode, dropNode)
      if (type === 'inner') {
        return (draggingNodeDepth + dropNode.data.catLevel) <= 3
      } else {
        console.log(draggingNodeDepth, dropNode.parent.level)
        return (draggingNodeDepth + dropNode.parent.level) <= 3
      }
    },
    getNodeDepth (node) {
      if (node.childrenList.length === 0) {
        return 1
      }
      let preDepth = this.getNodeDepth(node.childrenList[0])
      for (let item of node.childrenList) {
        return Math.max(preDepth, this.getNodeDepth(item)) + 1
      }
    }
  },
  created () {
    this.getCategoryList()
  }
}
</script>

<style scoped>
</style>